<template>
  <el-button type="danger" @click="del" size="large" style="margin: 10px 0">
    批量删除
  </el-button>

  <!-- 表格 -->
  <el-table
    :data="pagedData"
    @selection-change="selected"
    border
    style="width: 100%"
    :row-style="{ height: '48px' }"
    max-height="70vh"
  >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="id" label="编号" width="100"></el-table-column>
    <el-table-column prop="date" label="发布日期" width="180" sortable />
    <el-table-column prop="name" label="标题" width="180" />
    <!-- 内容列，点击展示 -->
    <el-table-column prop="address" label="内容" show-overflow-tooltip>
      <template #default="scope">
        <span
          style="cursor: pointer; color: #409eff"
          @click="showDetail(scope.row)"
        >
          {{ scope.row.address }}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="150">
      <template #default="scope">
        <template v-if="scope.row.id">
          <el-button
            size="small"
            type="primary"
            plain
            @click="edit(scope.$index, scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="remove(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </template>
    </el-table-column>
  </el-table>

  <!-- 公告详情弹窗 -->
  <el-dialog
    v-model="detailDialogVisible"
    width="700px"
    :close-on-click-modal="false"
    class="notice-detail-dialog"
  >
    <div class="notice-detail">
      <h2 class="notice-title">{{ detailData.name }}</h2>
      <p class="notice-date">{{ detailData.date }}</p>
      <div class="notice-content">
        {{ detailData.address }}
      </div>
    </div>
    <template #footer>
      <el-button type="primary" @click="detailDialogVisible = false">
        关闭
      </el-button>
    </template>
  </el-dialog>

  <!-- 编辑弹窗 -->
  <el-dialog v-model="editDialogVisible" title="编辑公告">
    <el-form :model="editForm" label-width="80px">
      <el-form-item label="发布日期">
        <el-date-picker
          v-model="editForm.date"
          type="date"
          placeholder="选择日期"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="editForm.name" />
      </el-form-item>
      <el-form-item label="内容">
        <el-input v-model="editForm.address" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmEdit">确认</el-button>
    </template>
  </el-dialog>

  <!-- 分页器 -->
  <Pagination
    v-model:currentPage="currentPage"
    v-model:pageSize="pageSize"
    :total="tableData.length"
    @change="loadData"
  />
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' // ✅ 加上 ElMessageBox
import useNoticeStore from '@/store/modules/notice'
import { storeToRefs } from 'pinia'
import { onMounted } from 'vue'

onMounted(() => {
  NoticeStore.tableData = NoticeStore.allData
})

let NoticeStore = useNoticeStore()
let { tableData } = storeToRefs(NoticeStore)

// 弹窗状态和表格数据
const editDialogVisible = ref(false)
const editForm = reactive({
  id: '',
  date: '',
  name: '',
  address: '',
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 补齐空行的计算属性
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  const pageItems = tableData.value.slice(start, end)

  const emptyCount = pageSize.value - pageItems.length
  if (emptyCount > 0) {
    for (let i = 0; i < emptyCount; i++) {
      pageItems.push({
        id: '',
        date: '',
        name: '',
        address: '',
      })
    }
  }

  return pageItems
})

const loadData = ({ page, pageSize }: { page: number; pageSize: number }) => {
  console.log('分页变化：', page, pageSize)
}

// 编辑事件
const edit = (index: number, row: any) => {
  editForm.id = row.id
  editForm.date = row.date
  editForm.name = row.name
  editForm.address = row.address
  editDialogVisible.value = true
}

// 编辑确认
const confirmEdit = async () => {
  try {
    await NoticeStore.updateNotice(editForm)
    ElMessage.success('修改成功')
    editDialogVisible.value = false
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

// 批量删除
let idArr: any = []
const del = async () => {
  if (idArr.length === 0) {
    return ElMessage.warning('请选择要删除的数据')
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${idArr.length} 条公告吗？`,
      '是否确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false,
      },
    )
    NoticeStore.removeBatch(idArr)
    ElMessage.success('删除成功')
    idArr = []
  } catch (err) {
    // 用户取消，不做处理
  }
}

// 多选框
const selected = (data: any) => {
  idArr = []
  data.forEach((value: any) => {
    if (value.id) {
      idArr.push(value.id)
    }
  })
}

// 单条删除
const remove = async (id: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条公告吗？', '是否确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
    })
    NoticeStore.removeNotice(id)
    ElMessage.success('删除成功')
  } catch (err) {
    // 用户取消
  }
}

// 公告详情弹窗
const detailDialogVisible = ref(false)
const detailData = reactive({
  id: '',
  date: '',
  name: '',
  address: '',
})

// 点击内容查看详情
const showDetail = (row: any) => {
  detailData.id = row.id
  detailData.date = row.date
  detailData.name = row.name
  detailData.address = row.address
  detailDialogVisible.value = true
}
</script>

<style scoped lang="scss">
.pagination-box {
  display: flex;
  justify-content: center;
}

.el-dialog {
  .el-form {
    .el-form-item {
      margin: 20px 0;
    }
  }
}

.notice-detail-dialog {
  .el-dialog__body {
    padding: 20px 30px;
    max-height: 65vh;
    overflow-y: auto;
  }
}

.notice-detail {
  .notice-title {
    text-align: center;
    font-size: 22px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .notice-date {
    text-align: right;
    color: #999;
    font-size: 14px;
    margin-bottom: 20px;
  }

  .notice-content {
    font-size: 16px;
    line-height: 1.8;
    color: #333;
    white-space: pre-wrap;
    /* 保留换行 */
    border: 1px solid rgb(93, 90, 90);
    border-radius: 10px;
    height: 30vh;
  }
}
</style>
